package com.anjie.powerproject.service.impl;

import com.anjie.powerproject.common.MockDataUtil;
import com.anjie.powerproject.entity.DeviceValue;
import com.anjie.powerproject.repository.DeviceValueRepository;
import com.anjie.powerproject.service.DeviceValueService;
import com.anjie.powerproject.strategy.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class DeviceValueServiceImpl implements DeviceValueService {
    @Autowired
    DeviceValueRepository deviceValueRepository;

    @Autowired
    MockDataUtil mockDataUtil;

    @Autowired
    Environment env;

    /**
     * 按时间区间以及设备code去获取合并后的当日的点位数据
     */
    @Override
    public List<DeviceValue> getDeviceValueByCodeAndDateRange(List<String> dateList, String deviceCode, Date startTime, Date endTime, boolean cover) {
        Date limitDate = DateUtils.plusOrMinusDay(endTime, 1).getTime();
        String start = DateUtils.ymdFormat.format(startTime);
        String end = DateUtils.ymdFormat.format(limitDate);

        List<DeviceValue> deviceValues = deviceValueRepository.getDeviceValues(deviceCode, start, end);
        if (cover) {
            return getDeviceValueAndCoverDate(dateList, deviceValues);
        }
        return deviceValues;
    }

    private List<DeviceValue> getDeviceValueAndCoverDate(List<String> dateList, List<DeviceValue> deviceValues) {
        Map<String, DeviceValue> deviceValueMap = deviceValues.stream().collect(Collectors.toMap(DeviceValue::getDate, e -> e));
        List<DeviceValue> deviceValueList = new ArrayList<>();
        for (String date : dateList) {
            DeviceValue deviceValue = deviceValueMap.get(date);
            if (deviceValue == null) {
                deviceValue = new DeviceValue();
                deviceValue.setData(0.0);
            }
            deviceValueList.add(deviceValue);
        }

        return deviceValueList;
    }

    @Override
    public Double getDeviceValueByCodeNow(String deviceCode) {
        String timeStr = DateUtils.ymdFormat.format(new Date());
        DeviceValue deviceValue = deviceValueRepository.getDeviceValueByTime(deviceCode, timeStr);
        if (deviceValue == null) {
            return null;
        }
        return deviceValue.getData();
    }

    @Override
    public Double getDeviceValueByDevIdNow(Integer devId) {
        String timeStr = DateUtils.ymdFormat.format(new Date());
        DeviceValue deviceValue = deviceValueRepository.getDeviceValueByTime(devId, timeStr);
        if (deviceValue == null) {
            return Double.NaN;
        }
        return deviceValue.getData();
    }
}
